/* 
 * File:   Operator.cpp
 * Author: Gab'z
 * 
 * Created on 28 mai 2012, 16:58
 */

#include "Operator.h"
#include "../../Context.h"
#include "../../memento/StackMemento.h"
#include "../../../exception/MementoException.h"
#include "../literal/Stack.h"

namespace calculator {

    Operator::Operator(const std::string name) : UndoableRedoableCommand(name) {
    }

    Operator::~Operator() {
    }

    void Operator::execute() const throw (CommandException) {
        try {
            eval(Context::getInstance()->getCurrentStack());
        } catch (CommandException& e) {
            throw;
        }
    }

    void Operator::restoreFromMemento(const Memento* memento) const throw (MementoException) {
        // on rempile le contenu du memento sur la pile courante
        const StackMemento* stackMemento = dynamic_cast<const StackMemento*> (memento);
        if (stackMemento == 0) {
            std::string str = "Bad Memento type, expected : StackMemento, was ";
            str += typeid (*memento).name();
            throw MementoException(str);
        }
        const Stack* stack = stackMemento->_stack;
        Context::getInstance()->getCurrentStack()->pop();
        for (unsigned int i = 0; i < stack->size(); i++) {
            Context::getInstance()->getCurrentStack()->push(stack->getConstant(i));
        }
    }
}
